<template>
  <div class="menu-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input
              v-model="queryParams.menuName"
              placeholder="请输入菜单名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-refresh" @click="handleExpandAll">展开/折叠</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="menuList"
        row-key="id"
        :tree-props="{ children: 'children' }"
        :default-expand-all="isExpandAll"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="菜单名称" prop="menuName" :show-overflow-tooltip="true">
          <template #default="scope">
            <span v-if="scope.row.icon" class="menu-icon">
              <el-icon>
                <component :is="scope.row.icon" />
              </el-icon>
            </span>
            {{ scope.row.menuName }}
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="orderNum" width="80" align="center" />
        <el-table-column label="权限标识" prop="perms" :show-overflow-tooltip="true" />
        <el-table-column label="路径" prop="path" :show-overflow-tooltip="true" />
        <el-table-column label="组件" prop="component" :show-overflow-tooltip="true" />
        <el-table-column label="类型" prop="menuType" width="80" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.menuType === 'M'" type="primary">目录</el-tag>
            <el-tag v-else-if="scope.row.menuType === 'C'" type="success">菜单</el-tag>
            <el-tag v-else-if="scope.row.menuType === 'F'" type="warning">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="80" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center" />
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" icon="el-icon-plus" @click="handleAdd(scope.row)">新增</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 菜单表单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ label: 'menuName', value: 'id' }"
            placeholder="选择上级菜单"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" controls-position="right" />
        </el-form-item>
        
        <el-form-item v-if="form.menuType !== 'F'" label="图标" prop="icon">
          <el-popover popper-class="icon-popover is-customized" :append-to-body="true" teleported placement="top" trigger="click" width="460">
            <template #reference>
              <el-input v-model="form.icon" placeholder="点击选择图标" readonly>
                <template #prefix>
                  <el-icon v-if="form.icon">
                    <component :is="form.icon" />
                  </el-icon>
                  <el-icon v-else><Plus /></el-icon>
                </template>
              </el-input>
            </template>
            <IconPicker v-model="form.icon" />
          </el-popover>
        </el-form-item>
        
        <el-form-item v-if="form.menuType !== 'F'" label="路由地址" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
        
        <el-form-item v-if="form.menuType === 'C'" label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径" />
        </el-form-item>
        
        <el-form-item v-if="form.menuType !== 'M'" label="权限标识" prop="perms">
          <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import IconPicker from '@/components/common/IconPicker.vue'

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 是否展开所有
const isExpandAll = ref(true)
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 菜单表格数据
const menuList = ref([])
// 菜单树选项
const menuOptions = ref([])

// 查询参数
const queryParams = reactive({
  menuName: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  parentId: 0,
  menuName: undefined,
  icon: undefined,
  menuType: 'M',
  orderNum: 0,
  path: undefined,
  component: undefined,
  perms: undefined,
  status: 1
})

// 表单校验
const rules = {
  menuName: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '显示排序不能为空', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由地址不能为空', trigger: 'blur' }
  ]
}

// 模拟数据
const mockMenuList = [
  {
    id: 1,
    menuName: '系统管理',
    icon: 'Setting',
    menuType: 'M',
    orderNum: 1,
    path: 'system',
    component: null,
    perms: null,
    status: 1,
    createTime: '2023-01-01 00:00:00',
    children: [
      {
        id: 2,
        menuName: '用户管理',
        icon: 'User',
        menuType: 'C',
        orderNum: 1,
        path: 'user',
        component: 'system/user/index',
        perms: 'system:user:list',
        status: 1,
        createTime: '2023-01-01 00:00:00',
        children: [
          {
            id: 6,
            menuName: '用户查询',
            icon: null,
            menuType: 'F',
            orderNum: 1,
            path: null,
            component: null,
            perms: 'system:user:query',
            status: 1,
            createTime: '2023-01-01 00:00:00'
          },
          {
            id: 7,
            menuName: '用户新增',
            icon: null,
            menuType: 'F',
            orderNum: 2,
            path: null,
            component: null,
            perms: 'system:user:add',
            status: 1,
            createTime: '2023-01-01 00:00:00'
          }
        ]
      },
      {
        id: 3,
        menuName: '角色管理',
        icon: 'UserFilled',
        menuType: 'C',
        orderNum: 2,
        path: 'role',
        component: 'system/role/index',
        perms: 'system:role:list',
        status: 1,
        createTime: '2023-01-01 00:00:00'
      },
      {
        id: 4,
        menuName: '菜单管理',
        icon: 'Menu',
        menuType: 'C',
        orderNum: 3,
        path: 'menu',
        component: 'system/menu/index',
        perms: 'system:menu:list',
        status: 1,
        createTime: '2023-01-01 00:00:00'
      },
      {
        id: 5,
        menuName: '部门管理',
        icon: 'Grid',
        menuType: 'C',
        orderNum: 4,
        path: 'dept',
        component: 'system/dept/index',
        perms: 'system:dept:list',
        status: 1,
        createTime: '2023-01-01 00:00:00'
      }
    ]
  }
]

// 查询菜单列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    menuList.value = mockMenuList
    loading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.parentId = 0
  form.menuName = undefined
  form.icon = undefined
  form.menuType = 'M'
  form.orderNum = 0
  form.path = undefined
  form.component = undefined
  form.perms = undefined
  form.status = 1
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.menuName = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 展开/折叠操作
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}

// 新增按钮操作
const handleAdd = (row) => {
  reset()
  if (row && row.id) {
    form.parentId = row.id
  }
  getMenuTree()
  open.value = true
  title.value = '添加菜单'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const menuId = row?.id || ids.value[0]
  // 模拟获取菜单详情
  const findMenuById = (list, id) => {
    for (let item of list) {
      if (item.id === id) {
        return item
      }
      if (item.children && item.children.length > 0) {
        const found = findMenuById(item.children, id)
        if (found) return found
      }
    }
    return null
  }
  
  const menuInfo = findMenuById(mockMenuList, menuId)
  if (menuInfo) {
    Object.assign(form, menuInfo)
  }
  
  getMenuTree()
  open.value = true
  title.value = '修改菜单'
}

// 获取菜单树
const getMenuTree = () => {
  // 模拟获取菜单树
  menuOptions.value = [
    {
      id: 0,
      menuName: '主目录',
      children: mockMenuList
    }
  ]
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const menuIds = row?.id ? [row.id] : ids.value
  
  ElMessageBox.confirm('确认删除已选中的菜单?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 菜单状态修改
const handleStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该菜单吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.menu-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.menu-icon {
  margin-right: 8px;
}

.icon-selector {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 12px;
  max-height: 260px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
  padding: 5px;
}

.icon-item:hover {
  background-color: #f5f7fa;
}

.icon-item i {
  font-size: 24px;
  margin-bottom: 5px;
}

.icon-item span {
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 100%;
  text-align: center;
}

/* 图标选择器弹出框样式 */
:deep(.icon-popover) {
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

/* 弹出方向自适应 */
:deep(.el-popper) {
  position: absolute !important;
}
</style> 